// utils/request.js
import tool from './tool.js'  

function request(url, method = "POST", params) {
    let promise = new Promise((resolve, reject) => {
        wx.showLoading({
            title: '数据加载中...',
            mask: true
        })

        // 获取存储的 token
        const token = tool.data.get('token')

        wx.request({
            url: url,
            method: method,
            data: params,
            header: {
                "content-Type": "application/json",
                "Authorization": token || ''  // 修改为 Authorization
            },
            success: (res) => {
                if (res.data.code === 401) {  
                    tool.data.remove('token')  
                    uni.navigateTo({
                        url: '/pages/mine/mine'
                    })
                }
                resolve(res.data)
            },
            fail: (error) => {
                reject(error)
            },
            complete() {
                wx.hideLoading()
            }
        })
    })
    return promise
}

module.exports = request